<?php

namespace app\api\model;

use app\admin\event\SystemLog;
use think\db\Query;
use think\Model;
use think\Db;

class SupplierModel extends Model
{

    protected static function init()
    {
        self::observe(SystemLog::class);
    }

    public function flow()
    {
        return $this->hasMany(SetAccountFlow::class, 'customer_id')->where('customer_type', 'supplier');
    }

    public function reconciliation()
    {
        return $this->hasMany(SupplierReconciliation::class, 'supplier_id');
    }

    public function inStock()
    {
        return $this->hasMany(InStock::class, 'supplier');
    }

    public function purchase()
    {
        return $this->hasMany(Purchase::class, 'supplier');
    }

    public function purchaseReturn()
    {
        return $this->hasMany(PurchaseReturn::class, 'supplier');
    }

    protected $table = 'jxc_supplier';

    public function searchNameAttr(Query $query, $value, $data)
    {
        $query->whereLike('name', '%' . $value . '%');
    }

    public function searchPhoneAttr(Query $query, $value, $data)
    {
        $query->whereLike('phone', '%' . $value . '%');
    }

    public function searchContactAttr(Query $query, $value, $data)
    {
        $query->whereLike('contact', '%' . $value . '%');
    }

    public function getList($data)
    {
        if (!empty($data)) {
            if (!empty($data['name'])) {
                $data[] = ['name', 'like', '$' . $data['name'] . '%'];
            }
            if (!empty($data['phone'])) {
                $data[] = ['phone', 'like', '%' . $data['phone'] . '%'];
            }
            if (!empty($data['contact'])) {
                $data[] = ['contact', 'like', '%' . $data['contact'] . '%'];
            }
            $list = $this->withSearch(array_keys($data), $data)->order('sort asc')
                ->page($data['page'], $data['size'])->paginate($data['size']);
        } else {
            $list = $this->order('sort asc')->page($data['page'], $data['size'])
                ->paginate($data['size']);
        }
        return $list;
    }

    public function getAll()
    {
        return $this->field('id,name,arrear')->order('id asc')->select();
    }

    public function getAdd($data)
    {
        return $this::create($data);
    }

    public function getInfo($id)
    {
        return $this->find($id);
    }

    public function getSupplierEdit($id, $data)
    {
        return self::where(['id' => $id])->update($data);
    }

    public function getSupplierDel($id)
    {
        $current = $this->find($id);
        if ((intval($current['arrear']) > 0)) {
            return false;
        } else {
            return self::where(['id' => $id])->delete();
        }
    }
}
